﻿using System;
using System.Collections.Generic;

using RexToy.DesignPattern;
using RexToy.UI.WinForm.Pmlx;

namespace RexToy.UI.WinForm.Controls
{
    public class ImageList : IStaticResource, IResourceContainer
    {
        private System.Windows.Forms.ImageList _list;
        public ImageList()
        {
            _list = new System.Windows.Forms.ImageList();
        }

        public string Key { get; set; }

        public object Target
        {
            get { return _list; }
        }

        public System.Windows.Forms.ColorDepth ColorDepth
        {
            get { return _list.ColorDepth; }
            set { _list.ColorDepth = value; }
        }

        public System.Drawing.Size ImageSize
        {
            get { return _list.ImageSize; }
            set { _list.ImageSize = value; }
        }

        public System.Drawing.Color TransparentColor
        {
            get { return _list.TransparentColor; }
            set { _list.TransparentColor = value; }
        }

        public void InitializeUri(string uri, PmlxDoc doc)
        {
            //Note:Nothing to do.
        }

        public void ParseContent(PmlxNode node)
        {
            foreach (var child in node.ChildNodes)
            {
                var res = child.LoadResourceElement();
                if (res is Icon)
                {
                    _list.Images.Add(res.Key, res.Target as System.Drawing.Icon);
                    continue;
                }

                if (res is Bitmap)
                {
                    _list.Images.Add(res.Key, res.Target as System.Drawing.Bitmap);
                    continue;
                }
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~ImageList()
        {
            Dispose(false);
        }

        private bool _disposed;
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
                return;

            if (disposing)
            {
                foreach (var item in _list.Images)
                {
                    IDisposable d = item as IDisposable;
                    if (d != null)
                        d.Dispose();
                }
                _list.Dispose();
            }

            _disposed = true;
        }
    }
}
